package name.flurl.android.tt_news4android;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import name.flurl.android.tt_news4android.util.ObjectSerializer;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class SitesPreference extends DialogPreference {

	private ArrayList<EditText> mSiteUrlEdits = new ArrayList<EditText>();
	private ArrayList<EditText> mSiteNameEdits = new ArrayList<EditText>();

	public SitesPreference(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public SitesPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		setPersistent(true);
	}

	protected View onCreateDialogView() {
		mSiteUrlEdits = new ArrayList<EditText>();
		mSiteNameEdits = new ArrayList<EditText>();

		ScrollView sv = new ScrollView(getContext());

		LinearLayout layout = new LinearLayout(getContext());
		layout.setOrientation(LinearLayout.VERTICAL);
		sv.addView(layout);

		LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		// LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
		// LinearLayout.LayoutParams.WRAP_CONTENT,
		// LinearLayout.LayoutParams.WRAP_CONTENT);
		// params1.gravity = Gravity.LEFT;
		// params1.weight = 1.0f;

		// LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(80,
		// LinearLayout.LayoutParams.WRAP_CONTENT);
		// params2.gravity = Gravity.RIGHT;
		//
		// LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(30,
		// LinearLayout.LayoutParams.WRAP_CONTENT);
		// params3.gravity = Gravity.CENTER;

		layout.setPadding(15, 5, 10, 5);
		// listview.setOrientation(LinearLayout.VERTICAL);

		// initialize the List of Maps
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

		ArrayList<String[]> prefArray = new ArrayList<String[]>();
		try {
			prefArray = (ArrayList<String[]>) ObjectSerializer
					.deserialize(getPersistedString(""));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (ClassCastException e) {
			e.printStackTrace();
		}
		int i = 0;
		if (prefArray != null) {
			for (i = 0; i < prefArray.size(); i++) {

				String[] pref = { "", "" };
				try {
					pref = prefArray.get(i);
				} catch (IndexOutOfBoundsException e) {
					pref[0] = "";
					pref[1] = "";
				}

				HashMap<String, String> map = new HashMap<String, String>();
				map.put("name", pref[0]);
				map.put("url", pref[1]);
				map.put("header", "Site " + (i + 1));
				list.add(map);
			}
		}
		// add an extra entry for creating new
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("name", "");
		map.put("url", "");
		map.put("header", "Site " + (i + 1));
		list.add(map);

		for (i = 0; i < list.size(); i++) {
			HashMap<String, String> site = list.get(i);
			LinearLayout row = (LinearLayout) inflater.inflate(
					R.layout.preference_site_urls_list_item, null);

			EditText siteNameEdit = (EditText) row
					.findViewById(R.id.PrefSiteUrlsListSiteNameEdit);
			EditText siteUrlEdit = (EditText) row
					.findViewById(R.id.PrefSiteUrlsListSiteUrlEdit);
			TextView siteHeaderText = (TextView) row
					.findViewById(R.id.PrefSiteUrlsListSiteHeader);

			siteNameEdit.setText(site.get("name"));
			siteUrlEdit.setText(site.get("url"));
			siteHeaderText.setText(site.get("header"));

			mSiteNameEdits.add(siteNameEdit);
			mSiteUrlEdits.add(siteUrlEdit);

			layout.addView(row);
		}

		// the from array specifies which keys from the map
		// we want to view in our ListView
		// String[] from = { "name", "url", "header" };

		// the to array specifies the TextViews from the xml layout
		// on which we want to display the values defined in the from array
		// int[] to = { R.id.PrefSiteUrlsListSiteNameEdit,
		// R.id.PrefSiteUrlsListSiteUrlEdit,
		// R.id.PrefSiteUrlsListSiteHeader };

		// create the adapter and assign it to the listview
		// SimpleAdapter adapter = new SimpleAdapter(getContext(), list,
		// R.layout.preference_site_urls_list_item, from, to);
		// mLayout.setAdapter(adapter);

		// for (i = 0; i < mListView.getChildCount(); i++) {
		// String siteName = ((EditText) mListView.getChildAt(i).findViewById(
		// R.id.PrefSiteUrlsListSiteNameEdit)).getText().toString()
		// .trim();
		// String siteUrl = ((EditText) mListView.getChildAt(i).findViewById(
		// R.id.PrefSiteUrlsListSiteUrlEdit)).getText().toString()
		// .trim();
		// ((EditText) mListView.getChildAt(i).findViewById(
		// R.id.PrefSiteUrlsListSiteNameEdit)).requestFocusFromTouch();
		// ((EditText) mListView.getChildAt(i).findViewById(
		// R.id.PrefSiteUrlsListSiteUrlEdit)).requestFocusFromTouch();
		// if (!(siteName.equals("") && siteUrl.equals(""))) {
		// String[] siteArray = { "", "" };
		// siteArray[0] = siteName;
		// siteArray[1] = siteUrl;
		// Log.i("tt_news oncreateview", siteName + "*" + siteUrl
		// + " childcount: " + mListView.getChildCount());
		// prefArray.add(siteArray.clone());
		// }
		// }

		layout.setId(android.R.id.widget_frame);

		return sv;
	}

	// @Override
	// protected Object onGetDefaultValue(TypedArray ta, int index) {
	//
	// int dValue = (int) ta.getInt(index, 50);
	//
	// return validateValue(dValue);
	// }

	@Override
	protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
		Log.i("tt_news hashtabpref", "initialVal");
		String temp = restoreValue ? getPersistedString("")
				: (String) defaultValue;

		if (!restoreValue)
			persistString(temp);

		// this.oldValue = temp;
	}

	// private int validateValue(int value) {
	//
	// if (value > maximum)
	// value = maximum;
	// else if (value < 0)
	// value = 0;
	// else if (value % interval != 0)
	// value = Math.round(((float) value) / interval) * interval;
	//
	// return value;
	// }

	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case DialogInterface.BUTTON_POSITIVE:
			updatePreference();
			break;

		default:
			break;
		}
	}

	private void updatePreference() {
		String newValue = "";
		ArrayList<String[]> prefArray = new ArrayList<String[]>();
		String siteName;
		String siteUrl;
		String[] siteArray = { "", "" };
		for (int i = 0; i < mSiteNameEdits.size(); i++) {
			siteName = mSiteNameEdits.get(i).getText().toString().trim();
			siteUrl = mSiteUrlEdits.get(i).getText().toString().trim();
			if (!(siteName.equals("") && siteUrl.equals(""))) {
				siteArray[0] = siteName;
				siteArray[1] = siteUrl;
				Log.i("tt_news updatePref siteconf", siteName + "*" + siteUrl
						+ " childcount: " + i);
				prefArray.add(siteArray.clone());
			}
		}

		try {
			newValue = ObjectSerializer.serialize(prefArray);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.i("tt_news updatePref", "setting pref value: " + newValue);
		persistString(newValue);
	}
}